/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.quangtin3;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.Logger;

/**
 * When accepted one connection, It makes new connection to destinal address.
 * Bouncing both socket to function as TCP relay.
 * @author quanghx
 */
public class Relay implements Runnable {

    private int port;
    private String caddr;
    private int cport;
    private ServerSocket serverSocket;
    private Logger log;

    public Relay(int port, String caddr, int cport, Logger log) {
        this.port = port;
        this.caddr = caddr;
        this.cport = cport;
        this.log = log;
    }

    public void run() {
        try {
            serverSocket = new ServerSocket(port);
            log.info("listening on " + port + " ...");
            int count = 0;
            while (true) {
                count++;
                log.info("wait for more connection");

                Socket sock_from = serverSocket.accept();
                log.info("accept (" + count + ") connection form " + sock_from);

                try {
                    Socket sock_to = new Socket(caddr, cport);
                    log.info("create bouncing");
                    new Bouncing(sock_from, sock_to, log);
                    new Bouncing(sock_to, sock_from, log);
                } catch (IOException e) {
                    log.warn("relay " + sock_from + " ");
                }
            }
        } catch (Exception e) {
            log.info("stop accept new relay for " + port + ":" + caddr + ":" + cport, e);
        }
    }
}
